package com.sgb.kjwl.view.ui.activity.transport.owner;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityTransportDriverLocationBinding;
import com.sgb.kjwl.databinding.DialogDriverLocation02Binding;
import com.sgb.kjwl.di.transport.DaggerTransportComponent;
import com.sgb.kjwl.di.transport.TransportModule;
import com.sgb.kjwl.model.entity.transport.TransportOrderEntity;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.viewmodel.transport.TransportDriverLocationViewModel;
import com.swgk.core.base.di.AppComponent;

import org.jetbrains.annotations.NotNull;

import javax.inject.Inject;

/**
 * @author: 杨畔
 * @date: 3/8/21 2:36 PM
 * @Description: 司机位置
 */
public class TransportDriverLocationActivity extends AppActivity implements AMap.OnMarkerClickListener {

    @Inject
    TransportDriverLocationViewModel mViewModel;
    private ActivityTransportDriverLocationBinding mBinding;
    //地图控制器
    private AMap aMap;
    //订单信息类
    private TransportOrderEntity mEntity;
    //司机弹窗
    private RoundCornerDialog mDialog;

    /**
     * 跳转司机位置
     */
    public static void start(@NonNull Context context, TransportOrderEntity entity) {
        Intent intent = new Intent(context, TransportDriverLocationActivity.class);
        intent.putExtra(RouterKey.DATA, entity);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTransportComponent.builder()
                .appComponent(appComponent)
                .transportModule(new TransportModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_transport_driver_location);
        mBinding.setLifecycleOwner(this);
        mBinding.mapTransportDriverLocation.onCreate(savedInstanceState);
        mBinding.actionBar.setOnBackClickListener(view -> finish());
        initMap();
        initEvent();
        initData();
    }

    /**
     * 初始化地图
     */
    private void initMap() {
        //获取地图控制类
        aMap = mBinding.mapTransportDriverLocation.getMap();
        //显示定位蓝点
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        //显示缩放控制器
        aMap.getUiSettings().setZoomControlsEnabled(false);
        //marker点击监听
        aMap.setOnMarkerClickListener(this);
    }

    private void initEvent() {
        mBinding.setOnClick(this);
    }

    private void initData() {
        mEntity = (TransportOrderEntity) getIntent().getSerializableExtra(RouterKey.DATA);
        syncLocation();
    }

    /**
     * 同步司机位置
     */
    private void syncLocation() {
        if (mEntity == null) return;
        addMarker(new LatLng(mEntity.getLatitude(), mEntity.getLongitude()), R.mipmap.ic_driver_location_marker, mEntity);
        //移动到当前位置
        cameraToPosition(mEntity.getLatitude(), mEntity.getLongitude());
        //展示弹窗
        showDriverDialog();
    }

    /**
     * 添加覆盖物
     */
    private void addMarker(LatLng latLng, @DrawableRes int drawable, TransportOrderEntity entity) {
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.icon(BitmapDescriptorFactory.fromResource(drawable));
        Marker marker = aMap.addMarker(markerOption);
        //设置附着对象
        marker.setObject(entity);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        //司机点击弹窗
        showDriverDialog();
        return false;
    }

    /**
     * 司机弹窗
     */
    private void showDriverDialog() {
        if (mDialog != null) {
            if (!mDialog.isShowing()) mDialog.show();
            return;
        }
        DialogDriverLocation02Binding binding = DataBindingUtil.inflate(LayoutInflater.from(this),
                R.layout.dialog_driver_location_02, null, false);
        mDialog = new RoundCornerDialog(this, binding.getRoot(), R.style.DialogTheme);
        mDialog.show();
        //设置内容
        if (mEntity != null) {
            //司机信息
            binding.tvDriverLocationTitle.setText(String.format("%s %s",
                    mEntity.getCarNumber(),
                    mEntity.getUserName()));
//            binding.tvDriverLocationContent.setText(String.format("%s%s%s%s",
//                    mEntity.getProvinceName(),
//                    mEntity.getCityName(),
//                    mEntity.getDistrictName(),
//                    mEntity.getDetailAddress()));
            //2.0.2.1改为只取详细地址
            binding.tvDriverLocationContent.setText(DefaultUtil.getString(mEntity.getDetailAddress()));
            if (TextUtils.isEmpty(mEntity.getDriverOwnerImAccount())) {
                binding.tvDriverLocationIm.setAlpha(0.5f);
                binding.tvDriverLocationIm.setEnabled(false);
            } else {
                binding.tvDriverLocationIm.setAlpha(1f);
                binding.tvDriverLocationIm.setEnabled(true);
            }
            if (TextUtils.isEmpty(mEntity.getTelPhone())) {
                binding.tvDriverLocationCall.setAlpha(0.5f);
                binding.tvDriverLocationCall.setEnabled(false);
            } else {
                binding.tvDriverLocationCall.setAlpha(1f);
                binding.tvDriverLocationCall.setEnabled(true);
            }
        }
        //设置监听
        binding.tvDriverLocationIm.setOnClickListener(this);
        binding.tvDriverLocationCall.setOnClickListener(this);
    }

    /**
     * 根据经纬度移动地图，标记中心点
     */
    private void cameraToPosition(double lat, double lng) {
        if (lat == 0 || lng == 0) return;
        //切换地图中心点
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 11));
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_driver_location_im) {
            // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
            buildSingleTalking(mEntity.getDriverOwnerImAccount());
        } else if (v.getId() == R.id.tv_driver_location_call) {
            //打电话
            showTelDialog(mEntity.getTelPhone());
        }
    }

    private void showTelDialog(String phone) {
        new RoundDialog.Builder(this)
                .title("确认拨号")
                .content(phone)
                .confirm("拨打")
                .cancelable(false)
                .confirmCallback(v -> {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    startActivity(intent);
                })
                .show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBinding.mapTransportDriverLocation.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mBinding.mapTransportDriverLocation.onPause();
    }

    @Override
    protected void onSaveInstanceState(@NotNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mBinding.mapTransportDriverLocation.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBinding.mapTransportDriverLocation.onDestroy();
    }
}
